<template>
  <div class="login-tabs">
    <h2>欢迎使用本系统</h2>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="账号登录" name="account">
        <el-form ref="loginForm" :model="loginForm" :rules="rules" class="login-form">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item>
            <div class="login-button">
              <el-button type="primary" size="large" @click="handleLogin">登录</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="手机验证登录" name="phone">
        <el-form ref="phoneLoginForm" :model="phoneLoginForm" :rules="rules" class="login-form">
          <el-form-item prop="phone">
            <el-input v-model="phoneLoginForm.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input v-model="phoneLoginForm.code" placeholder="请输入验证码"></el-input>
            <el-button
              type="text"
              class="get-code-btn"
              @click="handleGetCode"
              :disabled="isDisabled"
            >
              {{this.isDisabled
              ? `${this.secondsLeft}秒后重发`
              : "发送验证码"}}
            </el-button>
          </el-form-item>
          <el-form-item>
            <div class="login-button">
              <el-button type="primary" size="large" @click="handlePhoneLogin">登录</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <div class="login-other">
      <el-button type="text" @click="goToRegister">没有账号?去注册</el-button>
      <span class="login-divider">|</span>
      <el-button type="text" @click="goToForgetPassword">忘记密码？</el-button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      isDisabled: false, // 初始不禁用按钮
      lastClickTime: 0, // 存储最近一次点击时间戳
      secondsLeft: 0, // 倒计时秒数
      activeTab: "account", //标签切换
      loginForm: {
        username: "123",
        password: "123456",
      },
      phoneLoginForm: {
        phone: "",
        code: "",
      },

      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "密码长度在6到20个字符之间",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
    };
  },
  methods: {
    async handleLogin() {
      // 处理账号登录
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          // 验证码验证通过，跳转到下一个页面
          // 在这里提交表单
          await this.$axios
            .post("/api/user/login", this.loginForm)
            .then((res) => {
              if (res.data.code === 1) {
                localStorage.setItem("userToken", res.data.data);
                this.$message.success(res.data.msg);
                this.$router.replace({
                  name: "headerContent",
                  params: {
                    buttonState: "dropdown",
                  },
                });
              } else if (res.data.code === 0) {
                this.$message.error(res.data.msg);
              }
            })
            .catch((error) => {
              // 处理请求失败的错误
              if (!error.response) {
                this.$message.error(error.message);
              }
              this.$message.error(error.response.data.msg);
            });
        } else {
          this.$message.error("请正确填写信息");
          return false;
        }
      });
    },
    async handlePhoneLogin() {
      // 处理手机验证登录
      this.$refs.phoneLoginForm.validate(async (valid) => {
        if (valid) {
          // 验证码验证通过，跳转到下一个页面
          // 在这里提交表单
          await this.$axios
            .post("/api/user/login", this.phoneLoginForm)
            .then((res) => {
              if (res.data.code === 1) {
                localStorage.setItem("userToken", res.data.data);
                this.$message.success(res.data.msg);
                this.$router.replace({
                  name: "headerContent",
                  params: {
                    buttonState: "dropdown",
                  },
                });
              } else if (res.data.code === 0) {
                this.$message.error(res.data.msg);
              }
            })
            .catch((error) => {
              // 处理请求失败的错误
              this.$message.error(error.response.data.msg);
            });
        } else {
          this.$message.error("请正确填写信息");
          return false;
        }
      });
    },
    async handleGetCode() {
      // 处理获取验证码
      if (!this.phoneLoginForm.phone) {
        this.$message.error("请填写手机号码");
        return;
      }
      // this.countdownClick();
      // 调用后端接口发送验证码，这里使用假数据代替
      await this.$axios
        .post("/api/user/sendMsg?phone=" + this.phoneLoginForm.phone)
        .then((res) => {
          if (res.data.code == 1) {
            this.$notify({
              title: "获取验证码成功",
              message: res.data.msg,
              type: "success",
            });
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((error) => {
          // 处理请求失败的错误
          this.$message.error(error.response.data.msg);
        });
    },
    goToForgetPassword() {
      // 处理忘记密码
      this.$router.push("/forgotPassword");
    },
    goToRegister() {
      //处理新用户注册
      this.$router.push("/register");
    },
    // 倒计时60秒方法
    countdownClick() {
      // 点击触发60秒倒计时
      if (this.isDisabled) {
        return;
      }
      this.isDisabled = true; // 禁用按钮
      this.secondsLeft = 60; // 设置初始倒计时秒数
      this.lastClickTime = Date.now(); // 存储当前点击时间戳
      localStorage.setItem("lastClickTime", this.lastClickTime);
      this.countdown(); // 开始倒计时
    },
    // 开始倒计时
    countdown() {
      if (this.secondsLeft === 0) {
        this.isDisabled = false; // 解除禁用
        return;
      }
      this.secondsLeft--;
      setTimeout(() => {
        this.countdown();
      }, 1000); // 每一秒更新倒计时秒数
    },
    //获取时间戳
    getTimestamp() {
      const lastClickTime = localStorage.getItem("lastClickTime"); // 获取最近一次点击时间戳
      if (lastClickTime !== null && Date.now() - +lastClickTime < 60000) {
        // 如果距离上次点击时间小于60秒
        this.isDisabled = true; // 禁用按钮
        this.secondsLeft = Math.ceil(60 - (Date.now() - +lastClickTime) / 1000);
        this.countdown(); // 开始倒计时
      } else {
        this.isDisabled = false; // 不禁用按钮
        localStorage.removeItem("lastClickTime");
      }
    },
  },
  mounted() {
    this.getTimestamp();
  },
};
</script>
<style scoped>
.login-tabs {
  margin-bottom: 20px;
}

.login-form {
  margin-top: 20px;
}

.get-code-btn {
  float: right;
  margin-top: 5px;
}

.login-button {
  display: flex;
  flex-direction: column;
  /* align-items: center; */
}

.login-other {
  margin-top: 20px;
  text-align: center;
}

.login-divider {
  margin: 0 15px;
}
</style>